/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package src.view.customer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import org.primefaces.context.RequestContext;
import org.primefaces.event.CloseEvent;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;
import org.primefaces.model.UploadedFile;
import src.domain.customer.Customer;
import src.domain.security.Users;
import src.services.CRUEDService;
import src.services.customer.*;
import src.util.Constanta;
import src.util.Messager;
import src.util.Utils;
import src.view.security.LoginBean;
import src.view.system.ApprovalBean;


/**
 *
 * @author Lalugina
 */
@ManagedBean
@SessionScoped
public class CustApprovalBean {

    /**
     * Creates a new instance of CustApprovalBean
     */
    private LazyDataModel<Customer> customers;  
    
    private List<SelectItem> availableNationality,availableBusentype,availableCorebus,availableBuslic;
    private List<SelectItem> availableProvince,availableDistrict, availableResprovince, availableResdistrict;
    private List<SelectItem> availableReligion,availableEducation, availableMarstatus,availableSpouserel,
                availableIncomesrc,availableIncomeamt,availableOccu, avblJenis;
    private Customer selectedData;
    private UploadedFile uploadedFile;
    
    private static final int BUFFER_SIZE = 6124; 
    private Users user;
    private ApprovalBean approvalBean;
    
    public CustApprovalBean() {
        ambilUser();
        
        avblJenis = new ArrayList<>();
        avblJenis.add(new SelectItem(Constanta.CUSTTYPE_ANGGOTA, "Anggota Biasa"));
        avblJenis.add(new SelectItem(Constanta.CUSTTYPE_ANGGOTA_LB, "Anggota Luar Biasa"));
        
        FacesContext context = FacesContext.getCurrentInstance();
        approvalBean = (ApprovalBean) context.getApplication().evaluateExpressionGet(context, "#{approvalBean}", ApprovalBean.class);
        approvalBean.setUpdateTab(false);
        this.selectedData = null;
    }
    
    private boolean cekConfig() {
        return (user.getBranch().getBranchId()!=null ? true:false);
    }
    
    private void ambilUser() {
        FacesContext context = FacesContext.getCurrentInstance();
        LoginBean logBean = (LoginBean) context.getApplication().evaluateExpressionGet(context, "#{loginBean}", LoginBean.class);
        this.user = logBean.getSelectedUser();
    }
            
    public Customer getSelectedData() {
        return selectedData;
    }

    public List<SelectItem> getAvblJenis() {
        return avblJenis;
    }
        
    public void setSelectedData(Customer selectedData) {
        this.selectedData = selectedData;
    }

    public LazyDataModel<Customer> getCustomers() {
        return customers;
    }

    public UploadedFile getUploadedFile() {
        return uploadedFile;
    }

    public void setUploadedFile(UploadedFile uploadedFile) {
        this.uploadedFile = uploadedFile;
    }
    
    private void handleCountryChange(Integer country) {  
        if(country !=null ) {
            Map<String, String> filters = new HashMap<>();       
            filters.put("tb.countryId", String.valueOf(country.intValue()));
            ProvinceModel prov = new ProvinceModel();
            this.availableProvince = prov.listAll(filters);  
        } 
    }  
     
    private void handleProvinceChange(Integer province) {  
        if(province !=null ) {
            Map<String, String> filters = new HashMap<>();       
            filters.put("tb.provinceId", String.valueOf(province.intValue()));
            DistrictModel district = new DistrictModel();
            this.availableDistrict = district.listAll(filters);  
        } 
    }  
          
    private void handleRescountryChange(Integer country) {  
        if(country !=null ) {
            Map<String, String> filters = new HashMap<>();       
            filters.put("tb.countryId", String.valueOf(country.intValue()));
            ProvinceModel prov = new ProvinceModel();
            this.availableResprovince = prov.listAll(filters);  
        } 
    }  
     
    private void handleResprovinceChange(Integer province) {  
        if(province !=null ) {
            Map<String, String> filters = new HashMap<>();       
            filters.put("tb.provinceId", String.valueOf(province.intValue()));
            DistrictModel district = new DistrictModel();
            this.availableResdistrict = district.listAll(filters);  
        } 
    }  
        
    private void initForm(){
        availableBusentype = new BusentypeModel().listAll();
        availableCorebus = new CorebusModel().listAll();         
        availableBuslic = new BuslicModel().listAll();
        availableReligion = new ReligionModel().listAll();
        availableEducation = new EducationModel().listAll();
        availableNationality = new NationalityModel().listAll();
        availableMarstatus = new MarstatusModel().listAll();
        availableSpouserel = new SpouserelModel().listAll();
        availableIncomesrc = new IncomesrcModel().listAll();
        availableIncomeamt = new IncomeamtModel().listAll();
        availableCorebus = new CorebusModel().listAll();
        availableOccu = new OccuModel().listAll();
    }
    
    public void loadData() {
        customers = new LazyDataModel<Customer>() {

            @Override
            public List<Customer> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String,String> filters) { 
                                                
                int start = first;
                int end = first + pageSize;
                filters.put("approvalUid", "null");
                filters.put("suspended", "false");

                List<Customer> list = (List) new CRUEDService().loadLazy("Customer", start, end, sortField, sortOrder, filters);
                
                int recordCount = new CRUEDService().countLazy("Customer", filters);
                customers.setRowCount(recordCount);

                return list;
            }
        };
    }
    
    public void handleClose(CloseEvent event) {
        this.selectedData = null;
    }
    
    public void openData() {
        approvalBean.setUpdateTab(false);
        initForm();
        handleCountryChange(selectedData.getIdCountryId());
        handleProvinceChange(selectedData.getIdProvinceId());
        handleRescountryChange(selectedData.getResCountryId());
        handleResprovinceChange(selectedData.getResProvinceId());
    }
     
    private void save(boolean approved) {
        
        RequestContext context = RequestContext.getCurrentInstance();
        selectedData.setLogUpdated(Utils.logActions(user.getUserName(), new java.util.Date()));
        if (approved) {
            newNumber();
            selectedData.setApprovalUid(user.getUserId());
        
        } else selectedData.setSuspended(true);
        
        boolean success= new CustomerModel().saveData(selectedData);
        if (success==true) {
            loadData();
            approvalBean.updateTabOtor();
        }
                    
        Messager.showSaveUpdateStatus(success);
        context.addCallbackParam("success", success);
    }
    
    public void trySave(boolean approved) {
        boolean configured = cekConfig();
        if(configured==true) {
           save(approved);
            
        } else Messager.showWarning("unconfig");
    }
    
    public String selectItemValueOf(List<SelectItem> avblList, Integer id) {
        return (String) Utils.selectItemValueOf(avblList, id);
    }
        
    private void newNumber() {
        String cif = selectedData.getCif();
        if (cif.equals(Constanta.AUTO_NUMBERING)) {
            cif =  new CRUEDService().getNextTrxNumber(10, user.getBranch().getBranchId(), 0, 1).getTrxNum();
            selectedData.setCif(cif);
        }
    }
    
    public List<SelectItem> getAvailableBusentype() {
        return availableBusentype;
    }

    public List<SelectItem> getAvailableBuslic() {
        return availableBuslic;
    }

    public List<SelectItem> getAvailableCorebus() {
        return availableCorebus;
    }

    public List<SelectItem> getAvailableNationality() {
        return availableNationality;
    }

    public List<SelectItem> getAvailableDistrict() {
        return availableDistrict;
    }

    public List<SelectItem> getAvailableProvince() {
        return availableProvince;
    }

    public List<SelectItem> getAvailableResdistrict() {
        return availableResdistrict;
    }

    public List<SelectItem> getAvailableResprovince() {
        return availableResprovince;
    }

    public List<SelectItem> getAvailableEducation() {
        return availableEducation;
    }

    public List<SelectItem> getAvailableIncomeamt() {
        return availableIncomeamt;
    }

    public List<SelectItem> getAvailableIncomesrc() {
        return availableIncomesrc;
    }

    public List<SelectItem> getAvailableMarstatus() {
        return availableMarstatus;
    }

    public List<SelectItem> getAvailableOccu() {
        return availableOccu;
    }

    public List<SelectItem> getAvailableReligion() {
        return availableReligion;
    }

    public List<SelectItem> getAvailableSpouserel() {
        return availableSpouserel;
    }
    
}
